import React, { act, useEffect, useRef, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormTextArea,
  ProFormSelect,
  ProFormDateTimePicker
} from '@ant-design/pro-components';
import { Button, Form, List, message, Modal, Progress, Select, Slider, Space } from 'antd';
import { useIntl, FormattedMessage, useModel,useAccess} from '@umijs/max';
import { getAssetList,getdeviceNames ,getDeviceNumsByName} from '@/services/manage/asset';
import { getTaskList } from '@/services/manage/task';
import { generateRouteId, getPointList,addPoint } from '@/services/manage/route';
import { get } from 'lodash';
import { ReactSortable, Sortable } from 'react-sortablejs';
import ReactECharts from 'echarts-for-react';
import dayjs from 'dayjs';
import route from 'mock/route';



export type RouteFormData = Record<string, unknown> & Partial<API.Manage.Route>;

export type RouteFormProps = {
  onCancel: (flag?: boolean, formVals?: RouteFormData) => void;
  onSubmit: (values: RouteFormData) => Promise<void>;
  open: boolean;
  values: Partial<API.Manage.Route>;
}



const RouteForm: React.FC<RouteFormProps> = (props) => {
  const {onCancel, onSubmit, open} = props;
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 
  const [selectedPoints, setSelectedPoints] = useState<{ pointId: number; pointName: string }[]>([]);
  const [currentSelectId, setCurrentSelectId] = useState<number>();
  const [allPoints,setAllPoints] = useState<API.Manage.Point[]>([]); // 所有点位信息
  const routeId = useRef<number>(0); // 使用 useRef 来存储 routeId
  const getRouteID = async ()=>{
    await generateRouteId().then((res: { data: number }) => {
      routeId.current=res.data;
    }).catch(() => {
      message.error('获取路线ID失败');
    });
  }

  const getAllPoints = async () => {
    await getPointList().then((res) => {
      setAllPoints(res?.rows)
    }).catch(() => {
      message.error('获取点位失败');
    });
  }

  useEffect(() => {
    form.resetFields();   
    if (props.values.routeId) {
      routeId.current = props.values.routeId; // 使用 useRef 存储 routeId  
    } else {
      getRouteID();     
    }      
    console.log('props.values', props.values);    
    form.setFieldsValue({
      routeId: routeId.current,
      routeName: props.values.routeName ,
      routeLength: props.values.routeLength ,
      estimatedTime: props.values.estimatedTime ,
      pointSequence: allPoints // 初始化点位顺序
    });
  }, [form, props]);

  useEffect(() => {
    getAllPoints(); // 获取所有点位信息 
  }, []);

  const handleAddPoint = () => {
    if (!currentSelectId) {
      message.warning('请选择一个点位');
      return;
    }
    const newPoint = allPoints.find((p) => p.pointId === currentSelectId);
    if (!newPoint) return;

    const lastPoint = selectedPoints[selectedPoints.length - 1];
    if (lastPoint?.pointId === newPoint.pointId) {
      message.error('不能连续选择相同点位');
      return;
    }

    setSelectedPoints([...selectedPoints, newPoint]);
    setCurrentSelectId(undefined);
  };

  const handleRemove = (id: number, index: number) => {
    const newList = [...selectedPoints];
    newList.splice(index, 1);  
    // 检查删除后是否出现连续重复
    const hasConsecutiveDuplicates = newList.some((item, idx) => {
      return idx > 0 && item.pointId === newList[idx - 1].pointId;
    });  
    if (hasConsecutiveDuplicates) {
      message.error('删除后点位顺序中存在连续重复点位，请手动调整顺序');
      return;
    }  
    setSelectedPoints(newList.map(item => ({
      pointId: item.pointId,
      pointName: item.pointName,
    })));
  };

  const handleSortChange = (ids: number[]) => {
    const newList: { pointId: number; pointName: string }[] = [];
    ids.forEach((id) => {
      const count = selectedPoints.filter((p) => p.pointId === id).length;
      let used = 0;
      for (const p of selectedPoints) {
        if (p.pointId === id && used < count) {
          newList.push({ pointId: p.pointId, pointName: p.pointName });
          used++;
        }
      }
    });
    setSelectedPoints(newList.map(item => ({
      pointId: item.pointId,
      pointName: item.pointName,
    })));
  };

  const getChartOption = () => {
    const allPointData = allPoints?.map((p) => ({
      pointName: p?.pointName || '',
      value: [p.locationX, p.locationY],
    }));
  
    const selectedCoords = selectedPoints.map((p, index) => {
      const point = allPoints.find((pt) => pt.pointId === p.pointId);
      if (!point) return null;
      return {
        id: p.pointId,
        name: `${index + 1}. ${point.pointName}`,
        coord: [point.locationX, point.locationY],
      };
    }).filter(Boolean);
  
    // 构建 line 段对
    const linesData = [];
    for (let i = 0; i < selectedCoords.length - 1; i++) {
      linesData.push({
        coords: [
          selectedCoords[i]?.coord || [0, 0],
          selectedCoords[i + 1]?.coord || [0, 0],
        ],
      });
    }
  
    return {
      tooltip: { show: false },
      xAxis: {
        show: false,
        min: -50,      // 根据坐标范围设定偏移
        max: 400,      // 原来最大是 300，留点空间
      },
      yAxis: {
        show: false,
        min: -50,
        max: 150,      // 原来最大是 80，适当放大范围
      },
      grid: { left: 0, right: 0, top: 10, bottom: 10 },
      series: [
        // 所有点位
        {
          name: '全部点位',
          type: 'scatter',
          data: allPointData,
          symbolSize: 14,
          itemStyle: { color: '#999' },
          label: {
            show: true,
            formatter: (p: any) => p.data.pointName,
            position: 'bottom',
            color: '#999',
          },
          z: 1,
        },
        // 路径箭头线（中间显示箭头）
        {
          name: '路径箭头',
          type: 'lines',
          coordinateSystem: 'cartesian2d',
          data: linesData,
          effect: {
            show: true,
            symbol: 'arrow',
            symbolSize: 10,
            color: '#1890ff',
            constantSpeed: 40, // 箭头速度
            trailLength: 0,    // 不留轨迹
          },
          lineStyle: {
            color: '#1890ff',
            width: 2,
            opacity: 0.6,
            curveness: 0, // 直线
          },
          z: 2,
        },
        // 已选点位
        {
          name: '选中点位',
          type: 'scatter',
          data: selectedCoords.map((p) => ({
            name: p?.name,
            value: p?.coord,
          })),
          symbolSize: 16,
          itemStyle: { color: '#fa541c' },
          label: {
            show: true,
            formatter: (p: any) => p.data.pointName,
            position: 'top',
            fontWeight: 'bold',
            color: '#000',
          },
          z: 3,
        },
      ],
    };
  }; 

  const handleFinish = async (values: Record<string, any>) => {
    try {
      //生成路线信息  
      const routeFormData = {
        ...values,
        userId: currentUser?.userId,
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), 
        updateTime:  dayjs().format('YYYY-MM-DD HH:mm:ss'),  
      };
        await onSubmit(routeFormData);
        //添加路线点位关联信息
      if (selectedPoints.length !== 0) { 
        for (const p of selectedPoints) {
          const routePoint = {
            routeId: routeId.current, // 使用 useRef 获取当前的 routeId
            pointId: p.pointId,
            pointOrder: selectedPoints.indexOf(p) + 1, // 顺序从1开始
            userId: currentUser?.userId,
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), 
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),          
          };
          // console.log(routePoint);
          await addPoint(routePoint)
        }
        setSelectedPoints([]); // 清空已选点位
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败，请稍后重试');
    }        
  };
  
  

  return (
    <Modal
      width={640}
      title={props.values.routeId? '编辑路线':'新增路线'}
      forceRender
      open={open}
      onOk={()=>form.submit()} // 触发表单提交
      onCancel={()=>{
        form.resetFields();
        setSelectedPoints([]); 
        setCurrentSelectId(undefined);
        onCancel() // 关闭模态框
      }} 

    >
      <ProForm
        form={form}
        grid={true}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish} // 处理表单提交
        initialValues={{
          date: Date.now(),
          time: Date.now(),
        }}
        >
        <ProFormText
          name="routeId"
          label='路线ID'
          initialValue={routeId.current} // 随机生成一个ID
          rules={[
            {
              required: true,
              message: "请输入路线ID!",
            },
          ]}          
          readonly          
        />
        <ProFormText
          name="routeName"
          label='路线名称'
          placeholder="请输入路线名称"
          rules={[
            {
              required: true,
              message: "请输入路线名称!",
            },
          ]}
        />
        <ProFormDigit
          name="routeLength"
          label="路线长度（米）"
          placeholder="请输入路线长度"
          fieldProps={{ precision: 2 }}
          min={0}
          // readonly
        />
        <ProFormDigit
          name="estimatedTime"
          label="预计耗时（分钟）"
          placeholder="请输入预计耗时"
          min={1}
        />
        <ProForm.Item
          name="pointSequence"
          label="点位顺序（可重复/拖拽）"
          required
          // rules={[{ required: true, message: '请至少添加一个点位' }]}
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space>
              <Select
                style={{ width: 200 }}
                placeholder="选择点位"
                value={currentSelectId}
                onChange={setCurrentSelectId}
                options={allPoints?.map((p) => ({ label: p.pointName, value: p.pointId }))}
              />
              <Button type="primary" onClick={handleAddPoint}>
                添加点位
              </Button>
            </Space>

            <ReactSortable
              list={selectedPoints.map((point, index) => ({
                ...point,
                id: `${point.pointId}-${index}`, // Add unique id property
              }))}
              animation={150}
              setList={(newList) => {
                // 检查是否存在连续重复的点位
                const hasConsecutiveDuplicates = newList.some((item, idx) => {
                  return idx > 0 && item.pointId === newList[idx - 1].pointId;
                });
            
                if (hasConsecutiveDuplicates) {
                  message.error('拖拽结果中存在连续重复点位，请重新调整顺序');
                  return; // 拒绝更新列表
                }            
                setSelectedPoints(newList);
              }}
            >
              {selectedPoints.map((point, index) => (
                <li
                  key={`${point.pointId}-${index}`}
                  style={{
                    listStyle: 'none',
                    padding: '8px 12px',
                    marginBottom: 8,
                    background: '#1F1F1F',
                    border: '1px solid #ccc',
                    borderRadius: 4,
                    display: 'flex',
                    justifyContent: 'space-between',
                  }}
                >
                  <span>
                    {index + 1}. {point.pointName}
                  </span>
                  <a onClick={() => handleRemove(point.pointId, index)} style={{ color: 'red' }}>
                    删除
                  </a>
                </li>
              ))}
            </ReactSortable>
          </Space>
        </ProForm.Item>

      </ProForm>
      <h4 style={{fontSize:'20px'}}>点位坐标图</h4>
      <ReactECharts option={getChartOption()} style={{ height: 200,border:'2px solid #808080' ,borderRadius:'5px'}} />
    </Modal>
  );

};

export default RouteForm;